package revontuli.aMHD;

import java.util.ArrayList;

import revontuli.aMHD.R;
import revontuli.aMHD.UIhelpers.StopFinderListAdapter;
import revontuli.aMHD.dataclasses.Stop;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class StopFinderAct extends Activity {
	// pripojenie na GPS sluzbu
	private UserLocationSvc mService = null;
	private Messenger mReceiver;
	
	//nastavenia
	private SharedPreferences settings;
	int mMinSearchRange;
	int mMaxSearchRange;
	
	// objekty GUI
	private ListView mListView;
	private SeekBar mRangeSlider;
	private TextView mRangeLabel;
	private StopFinderListAdapter mListAdapter;

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			UserLocationSvc.ClientBinder binder = (UserLocationSvc.ClientBinder) service;
			mService = binder.getService();
			mService.registerMessenger(mReceiver);
		}

		public void onServiceDisconnected(ComponentName arg0) {
			mService = null;
		}
	};
	
	class IncomingHandler extends Handler {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case aMHDApp.MSG_REFRESH_GPS: // pozicia bola obnovena
				if (mService != null) {
					updateNearbyStopsList();
				}
				break;
			}
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stopfinder);
		
		//nacitanie nastaveni
		settings = PreferenceManager.getDefaultSharedPreferences(this);
		
		//vytvorenie spojenia medzi aktivitou a gps sluzbou
		mReceiver = new Messenger(new IncomingHandler());
		
		//nastavenie objektov gui
		mRangeLabel = (TextView)findViewById(R.id.rangeLabel);
		
		mRangeSlider = (SeekBar)findViewById(R.id.rangeSlider);
		this.mRangeSlider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				if (mService != null) {
					mService.setRange(progress + mMinSearchRange);
					updateRangeUI();
					updateNearbyStopsList();
				}
			}
		});
		
		//zoznam zastavok
		mListAdapter = new StopFinderListAdapter(this);
		mListView = (ListView)findViewById(R.id.stopFinderListView);
		mListView.setAdapter(mListAdapter);
		
	}

	@Override
	public void onStart() {
		super.onStart();
		if (aMHDApp.DEBUG) {
			Toast.makeText(getApplicationContext(), "finder bind", Toast.LENGTH_SHORT).show();
		}
		
		//pripojenie aktivity k GPS sluzbe
		bindService(new Intent(this, UserLocationSvc.class), mConnection, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		String max = settings.getString("settings_rangemax", Integer.toString(aMHDApp.MAX_SEARCH_RANGE));
		String min = settings.getString("settings_rangemin", Integer.toString(aMHDApp.MIN_SEARCH_RANGE));
		if (max == "") {
			max = Integer.toString(aMHDApp.MAX_SEARCH_RANGE);
		}
		if (min == "") {
			min = Integer.toString(aMHDApp.MIN_SEARCH_RANGE);
		}
		
		mMaxSearchRange = Integer.parseInt(max);
		mMinSearchRange = Integer.parseInt(min);
		updateRangeUI();
		updateNearbyStopsList();
	}
	
	@Override
	public void onStop() {
		super.onStop();
		//odpojenie sluzby
		if (mService != null) {
			unbindService(mConnection);
			if (aMHDApp.DEBUG) {
				Toast.makeText(getApplicationContext(), "finder unbind", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	//metody menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.stopfindermenu, menu);
		return true;
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (aMHDApp.mDataManager.getOffline()) { //offline mod
			//5-offline button, 6-online button
			menu.getItem(5).setVisible(false);
			menu.getItem(6).setVisible(true);
			menu.getItem(0).setEnabled(false);
			menu.getItem(1).setEnabled(false);
		} else { //online mod
			menu.getItem(5).setVisible(true);
			menu.getItem(6).setVisible(false);
			menu.getItem(0).setEnabled(true);
			menu.getItem(1).setEnabled(true);
		}
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.MenuSFMap:
			startActivity(new Intent(getApplicationContext(), StopMapAct.class));
			return true;
		case R.id.MenuSFConnection:
			startActivity(new Intent(getApplicationContext(), ConnFinderAct.class));
			return true;
		case R.id.MenuSFStopList:
			startActivity(new Intent(getApplicationContext(), StopListAct.class));
			return true;
		case R.id.MenuSFLineList:
			startActivity(new Intent(getApplicationContext(), LineListAct.class));
			return true;
		case R.id.MenuSFSettings:
			startActivity(new Intent(getApplicationContext(), SettingsAct.class));
			return true;
		case R.id.MenuSFOffline:
			aMHDApp.mDataManager.setOffline(true);
			return true;
		case R.id.MenuSFOnline:
			aMHDApp.mDataManager.setOffline(false);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	private void updateRangeUI() {
		mRangeSlider.setMax(mMaxSearchRange - mMinSearchRange);
		
		if (mService != null) {
			if (mService.getRange() < 1000) {
				mRangeLabel.setText(mService.getRange()+" "+getString(R.string.meters));
			} else {
				mRangeLabel.setText((double)Math.round(mService.getRange()/100) / 10 + " "+getString(R.string.kilometers));
			}
		} else {
			mRangeLabel.setText(Integer.toString(mMinSearchRange) + " " + getString(R.string.meters));
		}
	}
	
	private void updateNearbyStopsList() {
		if (mService != null) {
			ArrayList<Stop> zoznam = new ArrayList<Stop>();
			zoznam = aMHDApp.mDataManager.getNearbyStops(mService.getLocation(), mService.getRange());
			
			if ((zoznam != null)) {
				mListAdapter.fill(zoznam);
			}
		}
		mListAdapter.notifyDataSetChanged();
	}
}
